﻿#include "msghandlerwapper.h"
#include <QtCore/QMetaType>
#include <QtCore/QMutex>
#include <QtCore/QMutexLocker>
#include <QtCore/QCoreApplication>

#include <QDebug>
//#include <QMutex>
#include <QFile>
#include <QDir>
#include <QTextStream>
#include <QDateTime>

void outputMessage_Qt(QtMsgType type, const QMessageLogContext &context, const QString &msg)
{
    static QMutex mutex;

    QString text;
    switch(type)
    {
    case QtDebugMsg:
        text = QString("Debug:");
        break;

    case QtWarningMsg:
        text = QString("Warning:");
        break;

    case QtCriticalMsg:
        text = QString("Critical:");
        break;

    case QtFatalMsg:
        text = QString("Fatal:");
    }

    QString context_info = QString("File:(%1) Line:(%2)").arg(QString(context.file)).arg(context.line);
    QString current_date_time = QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss ddd");
    QString message = QString("%1 %2 %3 %4").arg(text).arg(context_info).arg(msg).arg(current_date_time);

    if( !QMetaObject::invokeMethod(MsgHandlerWapper::instance(), "LogMessageSig" , Q_ARG(QtMsgType, type), Q_ARG(QString, current_date_time) , Q_ARG(QString, msg)) )
    {
        message += ";emit LogMessageSig failed!";
    }

    QFile file("./QtLog/QtLog.txt");
    mutex.lock();
    if( file.open(QIODevice::WriteOnly | QIODevice::Append) )
    {
        QTextStream text_stream(&file);
        text_stream << message << "\r\n";
        file.flush();
    }
    file.close();

    mutex.unlock();
}

MsgHandlerWapper * MsgHandlerWapper::m_instance = 0;

MsgHandlerWapper * MsgHandlerWapper::instance()
{
    static QMutex mutex;
    if (!m_instance)
    {
        QMutexLocker locker(&mutex);
        if (!m_instance)
            m_instance = new MsgHandlerWapper;
    }
    return m_instance;
}

MsgHandlerWapper::MsgHandlerWapper() :QObject(qApp)
{
    qRegisterMetaType<QtMsgType>("QtMsgType");
    qInstallMessageHandler(outputMessage_Qt);
}
